const express = require("express");
const expressWs = require("express-ws");
const logger = require("morgan");
const cors = require("cors");
const fileUpload = require("express-fileupload");

const indexRouter = require("./routes/index");
const apiRouter = require("./routes/api");

const app = express();
expressWs(app);
app.use(fileUpload());
app.use(cors());
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use("/static", express.static("public"));
app.use("/", indexRouter);
app.use("/api", apiRouter);
app.ws("/msg", function (ws, req) {
  console.log("connect success");
  ws.send("connect to express server with WebSocket success");
  ws.on("message", function (msg) {
    ws.send(`default response: ${msg}`);
  });
  // let timer = setInterval(() => {
  // 	ws.send(`interval message ${new Date()}`)
  // }, 2000)
  ws.on("close", function (e) {
    console.log("close connection");
    // clearInterval(timer)
    // timer = undefined
  });
  app.locals.ws = ws;
});
app.listen(3004, () => {
  console.log(`express server listen at http://localhost:3004`);
});
